package com.huanxing.cloud.mall.api.redis;

import cn.hutool.core.util.ObjectUtil;
import com.huanxing.cloud.common.core.constant.CacheConstants;
import com.huanxing.cloud.common.core.constant.CommonConstants;
import com.huanxing.cloud.mall.api.service.IOrderInfoService;
import com.huanxing.cloud.mall.common.entity.OrderInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * redis 监听器
 *
 * @author lijx
 * @since 2022/3/8 13:20
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

  private final IOrderInfoService orderInfoService;

  public RedisKeyExpirationListener(
      RedisMessageListenerContainer listenerContainer, IOrderInfoService orderInfoService) {
    super(listenerContainer);
    this.orderInfoService = orderInfoService;
  }

  @Override
  public void onMessage(Message message, byte[] pattern) {
    String expiredKey = message.toString();
    // 订单自动取消
    if (expiredKey.contains(CacheConstants.MALL_ORDER_STATUS)) {
      expiredKey = expiredKey.replace(CacheConstants.MALL_ORDER_STATUS, "");
      OrderInfo orderInfo = orderInfoService.getById(expiredKey);
      // 只有待支付的订单能取消
      if (ObjectUtil.isNotNull(orderInfo) && CommonConstants.NO.equals(orderInfo.getPayStatus())) {
        orderInfoService.cancelOrder(orderInfo);
      }
    }
  }
}
